package com.example.monitorsms.service;


import android.app.Notification;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;

import com.example.monitorsms.MyApp;
import com.example.monitorsms.utils.LogUtils;
import com.example.monitorsms.utils.StringUtils;

public class MyNotificationListenerService extends NotificationListenerService {
    private String nMessage;

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            String msgString = (String) msg.obj;
            LogUtils.e("KEVIN", "msgString" + "-----" + msgString);
            if (!StringUtils.isEmpty(msgString) && (msgString.contains(MyApp.tipsOk) || msgString.contains(MyApp.PushOk))) {
                new Handler().postDelayed(() -> {
                    MyApp.setRouse();
                }, 2000);
                new Handler().postDelayed(() -> {
                    MyApp.setPlayer();
                    MyApp.setVibrate();
                    LogUtils.e("SmsRecevier", "开始震动了");
                }, 5000);

                new Handler().postDelayed(() -> {
                    LogUtils.e("SmsRecevier", "是否震动了");
                    if (MyApp.vibrator.hasVibrator()) {
                        LogUtils.e("SmsRecevier", "是的震动了");
                        MyApp.vibrator.cancel();
                    }
                }, 20000);
            }
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    //当系统收到新的通知后出发回调
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        super.onNotificationPosted(sbn);
        // 获取通知内容
        Notification notification = sbn.getNotification();
        if (notification != null) {
            // 获取通知标题和内容
            String title = notification.extras.getString(Notification.EXTRA_TITLE);
            String content = notification.extras.getString(Notification.EXTRA_TEXT);

            LogUtils.e("KEVIN", "Get title" + "-----" + title);
            LogUtils.e("KEVIN", "Get content" + "-----" + content);

            // 在这里处理通知内容
            nMessage = title + content;
            Message obtain = Message.obtain();
            obtain.obj = nMessage;
            mHandler.sendMessage(obtain);
        }
    }

    //当系统通知被删掉后出发回调。
    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        super.onNotificationRemoved(sbn);
    }
}
